import { ResponseProp, Vo } from "src/utils/Vo";
import * as qiniu from "qiniu";
import * as dayjs from "dayjs";
import { auth } from "qiniu";
import Mac = auth.digest.Mac;

export class QiniuTool {
  // 资源域名
  public domain:string = "";
  // 七牛云accessKey
  public accessKey:string = "";
  // 七牛云secretKey
  public secretKey:string = "";
  // 七牛云空间名
  public scope:string = "";
  // 过期时间，s为单位
  public expires:number = 7200;
  // form表单上传器
  private formUploader = null;
  // 七牛云mac
  private mac:Mac = null;
  // 上传token
  private uploadToken:string = "";
  // 七牛云配置
  private config = {};
  // 七牛云putExtra
  private putExtra = null;

  constructor(config:Config={}) {
    if(config.domain) this.domain = config.domain;
    if(config.accessKey) this.accessKey = config.accessKey;
    if(config.secretKey) this.secretKey = config.secretKey;
    if(config.scope) this.scope = config.scope;
    if(config.expires) this.expires = config.expires;
    this.initMake();
  }

  private initMake() {
    this.makeToken();
    this.makeConfig();
    this.makeFormUploader();
    this.makePutExtra();
  }

  // 字节数组上传
  put(file):Promise<ResponseProp>{
    return new Promise((resolve) => {
      this.formUploader.put(this.uploadToken,`${this.getFolderName()}/${file.originalname}`,file.buffer,this.putExtra,function(respErr,respBody, respInfo) {
        if (respErr) throw respErr;
        if (respInfo.statusCode == 200) {
          return resolve(Vo.success(respInfo.data));
        } else {
          return resolve(Vo.error("上传失败",{ respInfo, respBody }))
        }
      })
    })
  }

  // 获取私有空间外链
  getDownUrl(key:string) {
    const bucketManager = new qiniu.rs.BucketManager(this.mac, this.config);
    // 过期时间：2天
    const deadline = Math.floor(Date.now() / 1000) + 3600 * 48;
    return bucketManager.privateDownloadUrl(this.domain, key, deadline);
  }

  // 生成Token
  private makeToken() {
    this.mac = new qiniu.auth.digest.Mac(this.accessKey, this.secretKey);
    const putPolicy = new qiniu.rs.PutPolicy({
      scope: this.scope,
      expires: this.expires,
      returnBody:JSON.stringify({
        bucket:"$(bucket)",
        fname:"$(fname)",
        key:"$(key)",
        fsize:"$(fsize)",
        mimeType:"$(mimeType)",
        imageInfo:{
          format:"$(imageInfo.format)",
          width:"$(imageInfo.width)",
          height:"$(imageInfo.height)",
        },
      })
    });
    this.uploadToken = putPolicy.uploadToken(this.mac);
  }

  // 生成config
  private makeConfig() {
    const config:any = new qiniu.conf.Config();
    config.zone = qiniu.zone.Zone_z1;
    this.config = config;
  }

  // 生成form表单上传器
  private makeFormUploader() {
    this.formUploader = new qiniu.form_up.FormUploader(this.config);
  }

  // 生成putExtra
  private makePutExtra() {
    this.putExtra = new qiniu.form_up.PutExtra();
  }

  // 获取目录名
  private getFolderName() {
    return `${dayjs().year()}/${dayjs().format("MMDD")}`;
  }
}

export interface Config {
  // 资源域名
  domain?:string;
  // 七牛云accessKey
  accessKey?:string;
  // 七牛云secretKey
  secretKey?:string;
  // 七牛云空间名
  scope?:string;
  // 过期时间，s为单位
  expires?:number;
}